<template>
  <div class="container">
    <div class="app-container">
      <el-card>
        <el-tree
          default-expand-all
          :data="attribute"
          :props="defaultProps"
          class="tree"
          :expand-on-click-node="false"
        >
          <template v-slot="{ node, data }">
            <el-row type="flex" justify="space-between" style="width: 100%">
              <el-col>{{ data.name }}</el-col>
              <el-col :span="4">
                <span class="manager">{{ data.managerName }}</span>
                <el-dropdown @command="commandChange($event,data.id)">
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add"
                      >添加子部门</el-dropdown-item
                    >
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 弹出层 -->

    <el-dialog
      :title="type == 'add' ? '添加新部门' : '编辑部门'"
      :visible.sync="ShowDialog"
      @open="handlerOpen"
    >
      <el-form
        label-width="120px"
        :model="departmentInfo"
        :rules="rules"
        ref="form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
            placeholder="2-10个字符"
            size="mini"
            v-model="departmentInfo.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input
            placeholder="2-10个字符"
            size="mini"
            v-model="departmentInfo.code"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select
            placeholder="请选择负责人"
            style="width: 100%"
            size="mini"
            v-model="departmentInfo.managerId"
          >
            <el-option
              v-for="item in departmentLeaderList"
              :key="item.id"
              :value="item.id"
              :label="item.username"
            ></el-option>

            <!-- <el-option label="333"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            placeholder="1-100个字符"
            size="mini"
            type="textarea"
            :rows="4"
            v-model="departmentInfo.introduce"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item style="text-align: center;"> -->
        <div style="text-align: center">
          <el-button type="primary" size="small" @click="comform"
            >确定</el-button
          >
          <el-button type="danger" size="small" @click="ShowDialog = false"
            >取消</el-button
          >
        </div>

        <!-- </el-form-item> -->
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
//引入接口
import { getDepartmentList, getDepartmentLeaderList,addOrUpdateDepartment,getDepartmentDetail,deleteDepartment } from "@/api/department";
//引入方法
import { listToTree } from "@/utils";

export default {
  name: "Department",
  data() {
    return {
      attribute: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
      //部门数据收集
      departmentInfo: {
        //编码
        code: "",
        //介绍
        introduce: "",
        //负责人名称
        managerId: "",
        //部门名称
        name: "",
        //父节点的id
        pid: "",
      },
      //规则对象
      rules: {
        name: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
          { min: 2, max: 10, message: "部门名称长度为2-10个字符" },
          {validator: this.checkCode1, trigger: "blur"}
        ],
        code: [
          { required: true, message: "请输入部门编码", trigger: "blur" },
          { min: 2, max: 10, message: "部门编码长度为2-10个字符" },
          {validator: this.checkCode, trigger: "blur"}
        ],
        introduce: [
          { required: true, message: "请输入部门介绍", trigger: "blur" },
          { min: 2, max: 100, message: "部门介绍长度为2-100个字符" },
        ],
        managerId: [
          { required: true, message: "请选择负责人", trigger: "blur" },
        ],
      },
      //负责人列表
      departmentLeaderList: [],
      //控制子组件的显示与隐藏
      ShowDialog: false,
      //类型
      type: "add",
    };
  },
  //挂载时调用接口
  mounted() {
    this.HasDepartment();
  },
  methods: {
    //获取数据
    async HasDepartment() {
      let result = await getDepartmentList();
      this.attribute = listToTree(result, 0);
    },
    //获取负责人列表
    async HasDepartmentLeader() {
      let result = await getDepartmentLeaderList();
      this.departmentLeaderList = result;
    },
    //节点事件
    async commandChange(command,id) {
    
    if(command=='add'||command=='edit') {
        //显示对话框
        this.ShowDialog = true;
    }
      if (command == "add") {
          //收集数据
      this.departmentInfo.pid = id
        this.type = "add";
      } else if (command == "edit") {
        this.type = "edit";
        let result = await getDepartmentDetail(id);
        //合并数据
        Object.assign(this.departmentInfo, result);
      }
      else if (command == 'del') {
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
      }).then( async ()=>{
        //调用接口
        await deleteDepartment(id)
        //提示
        this.$message({
          type:'success',
          message:'删除成功!'
        })
        //获取数据
        this.HasDepartment()
      }).catch(()=>{
        //提示
        this.$message({
          type:'info',
          message:'已取消删除'
        })
      })
    }
    },
    //对话框打开的回调
    handlerOpen() {
      this.$nextTick(() => {
        //重置表单
        this.$refs.form.resetFields();
      });
      //获取负责人的信息
      this.HasDepartmentLeader();
    },
    //自定义校验规则
    async checkCode(rules, value, callback) {
      let result = await getDepartmentList()
      if(this.type=='edit') {
        result = result.fliter(item => item.id !== this.departmentInfo.id)
      }
      if(result.some(item =>item.code == value)) {
        callback(new Error("部门编号已存在"));
       
      }else {
        callback()
      }
      
    },
    async checkCode1(rules, value, callback) {
      let result = await getDepartmentList()
      if(this.type=='edit') {
        result = result.fliter(item => item.name !== this.departmentInfo.name)
      }
      if(result.some(item =>item.name == value)) {
        callback(new Error("部门名称已存在"));
       
      }else {
        callback()
      }
      
    },
    //确定按钮的回调
    async comform() {
      //调用表单方法，判断表单校验
      this.$refs.form.validate();
      //发请求
      await addOrUpdateDepartment(this.departmentInfo)
      //提示
      this.$message({
        type:'success',
        message:this.departmentInfo.id?'修改成功':'添加成功'
      })
      //关闭对话框
      this.ShowDialog = false;
      //重新获取数据
      this.HasDepartment();
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  margin: 30px 60px;
  .tree {
    font-size: 13px;
  }
  .manager {
    display: inline-block;
    width: 60px;
    margin: 0px 20px;
  }
}
</style>
